<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <el-card class="box-card">
      <div class="search">
        <el-input
          placeholder="请输入内容"
          v-model="paramsObj.query"
          clearable
          class="input-with-select"
          @clear="clearFn"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchBtn"></el-button>
        </el-input>&nbsp;&nbsp;
        <!-- 添加用户的按钮 -->
        <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>

        <!-- 添加用户弹出框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          :destroy-on-close="true"
          width="60%"
          :before-close="handleClose"
        >
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            label-width="80px"
            :rules="rules"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="ruleForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="quxiao1">取 消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 添加用户弹出框 -->
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" :border="true" style="width: 100%">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column label="邮箱" prop="email" width="180"></el-table-column>
        <el-table-column label="电话" prop="mobile" width="180"></el-table-column>
        <el-table-column label="角色" prop="role_name" width="180"></el-table-column>
        <el-table-column label="转态" prop="name" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#dcdfe6"
              @change="userType(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="250">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑此用户" placement="top">
              <el-button type="primary" @click="alterUser(scope.row)">
                <i class="el-icon-edit"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除此用户" placement="top">
              <el-button type="danger" @click="removeUser(scope.row.id)">
                <i class="el-icon-delete"></i>
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="修改此用户角色" placement="top">
              <el-button type="warning">
                <i class="el-icon-s-tools"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

        <!-- 编辑弹出层 -->
      <el-dialog
        title="编辑"
        :visible.sync="alter_dialogVisible"
        width="60%"
        :before-close="alter_handleClose"
        :destroy-on-close='true'
      >
        <!-- 表单 -->
        <el-form :model="alter_ruleForm" :rules="rules" ref="alter_ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名">
            <el-input v-model="alter_ruleForm.username"  :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="alter_ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="alter_ruleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 表单 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="quxiao">取 消</el-button>
          <el-button type="primary" @click="redactBtn('alter_ruleForm')">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsObj.pagenum"
        :page-sizes="[4, 6, 8, 10]"
        :page-size="paramsObj.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>
<script>
import { usersApi, addUsersApi, usersTypeApi, removeUserApi, alterUserApi } from '@/api'
export default {
  data () {
    return {
      tableData: [],
      value: false,
      total: 0,
      paramsObj: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      dialogVisible: false,
      // 添加用户校验规则
      rules: {
        // 用户名验证规则
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 12,
            message: '用户名长度在 3 到 12 个字符',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (this.tableData.some((item) => item.username === value)) {
                callback(new Error('用户名被占用'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        // 密码验证规则
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        // 手机号的验证规则
        mobile: [
          {
            validator: (rule, value, callback) => {
              const regexp =
                /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              console.log(value)
              if (value === '') {
                callback()
              } else if (regexp.test(value)) {
                callback()
              } else {
                console.log(3)
                callback(new Error('请输入正确的手机号'))
              }
            },
            trigger: 'blur'
          }
        ],
        // 邮箱的验证规则
        email: [
          {
            validator: (rule, value, callback) => {
              const regexp = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (value === '') {
                callback()
              } else if (regexp.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的邮箱'))
              }
            },
            trigger: 'blur'
          }
        ]
      },
      alter_dialogVisible: false,
      alter_ruleForm: {
        username: '',
        email: '',
        mobile: ''
      },
      alter_rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 获取用户列表的数据
    this.getUsers()
  },
  methods: {
    // 请求数据API
    async getUsers () {
      const res = await usersApi(this.paramsObj)
      this.tableData = res.data.data.users
      this.total = res.data.data.total
    },
    // 每页多少条
    handleSizeChange (val) {
      this.paramsObj.pagesize = val
      this.getUsers()
    },
    // 第几页
    handleCurrentChange (val) {
      this.paramsObj.pagenum = val
      this.getUsers()
    },
    // 搜索
    searchBtn () {
      this.getUsers()
    },
    // 清空搜索框时搜索一下
    clearFn () {
      this.getUsers()
    },
    // 关闭添加用户弹出层
    handleClose (done) {
      this.ruleForm.username = ''
      this.ruleForm.password = ''
      this.ruleForm.email = ''
      this.ruleForm.mobile = ''
      done() // done()  关闭弹出层
    },
    // 添加用户提交
    submitForm (formName) {
      this.$refs[formName].validate((valid, object) => {
        if (valid) {
          addUsersApi(this.ruleForm).then((res) => {
            this.getUsers()
            this.dialogVisible = false
            console.log(res.data.meta.status)
            if (res.data.meta.status === 201) {
              this.$message({
                message: res.data.meta.msg,
                type: 'success'
              })
            } else {
              this.$message.error(res.data.meta.msg)
            }
          })
        } else {
          return false
        }
      })
    },
    // 修改状态
    userType (row) {
      usersTypeApi(row.id, row.mg_state).then((res) => {
        console.log(res.data.meta.status)
        if (res.data.meta.status === 200) {
          this.$message({
            message: res.data.meta.msg,
            type: 'success'
          })
        } else {
          this.$message.error(res.data.meta.msg)
        }
      })
    },
    // 删除用户
    removeUser (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeUserApi(id).then((res) => {
            if (res.data.meta.status === 200) {
              this.getUsers()
              this.$message({
                message: res.data.meta.msg,
                type: 'success'
              })
            } else {
              this.$message.error(res.data.meta.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑此用户
    alterUser (row) {
      this.alter_dialogVisible = true
      console.log(row)
      this.alter_ruleForm = row
    },
    alter_handleClose (done) {
      this.getUsers()
      done()
    },
    quxiao1 () {
      this.ruleForm.username = ''
      this.ruleForm.password = ''
      this.ruleForm.email = ''
      this.ruleForm.mobile = ''
      this.dialogVisible = false
    },
    quxiao () {
      this.alter_dialogVisible = false
      this.getUsers()
    },
    redactBtn (formName) {
      alterUserApi(this.alter_ruleForm).then(res => {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (res.data.meta.status === 200) {
              this.alter_dialogVisible = false
              this.getUsers()
              this.$message({
                message: res.data.meta.msg,
                type: 'success'
              })
            }
          } else {
            this.alter_dialogVisible = true
          }
        })
      })
    }
  }
}
</script>
<style lang='less' scoped>
.search {
  display: flex;
  margin-bottom: 15px;
  span {
    position: relative;
  }
}
.el-input-group {
  width: 500px !important;
}
</style>
